package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

//自定义切面，拦截加了AutoFill注解的方法
@Aspect
@Component
@Slf4j
public class AutoFillAspect {
    //切入点
    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
    public void autoFillPointCut(){}

    //前置通知，进行公共字段的赋值
    @Before("autoFillPointCut()")
    public void autoFill(JoinPoint joinPoint){
        log.info("开始自动填充");

        //获取当前被拦截的方法上加了AutoFill注解的参数
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class);//获取注解对象
        OperationType operationType = autoFill.value();

        //获取当前被拦截的方法的参数
        Object[] args = joinPoint.getArgs();
        if(args == null || args.length == 0){
            return;
        }
        Object object = args[0];

        //设置公共字段
        Long currentId = BaseContext.getCurrentId();
        LocalDateTime now = LocalDateTime.now();

        //根据当前不同的操作类型，为对应的属性进行赋值
        if(operationType == OperationType.INSERT){
            try {
                Method setCreateTime =object.getClass().getDeclaredMethod("setCreateTime", LocalDateTime.class);
                setCreateTime.invoke(object, now);
                object.getClass().getDeclaredMethod("setCreateUser", Long.class).invoke(object, currentId);
                object.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class).invoke(object, now);
                object.getClass().getDeclaredMethod("setUpdateUser", Long.class).invoke(object, currentId);

            }catch (Exception e) {
                e.printStackTrace();
            }
        }else if(operationType == OperationType.UPDATE){
            try {
                object.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class).invoke(object, now);
                object.getClass().getDeclaredMethod("setUpdateUser", Long.class).invoke(object, currentId);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
}
